var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
export const testUrl = "http://127.0.0.1";


export function getMyId(){
  return askJson(testUrl + "/account/api/user/0/").then((d) => {
    if (d.code) {
      showMessage("您当前尚未登录，2秒后自动跳转到登录界面")
      // setTimeout(()=>{
      //   window.location.href = testUrl +  "/account/wxlogin/?next=/web/IM/index.html";
      // },2000);
    }
    else {
      return d.id;
    }
  })
}


//获取登录签名
export function getSign() {
  let timestamp = Math.round(new Date().getTime() / 1000);
  let nonce = Math.random().toString(36).slice(-12);
  let res = { timestamp, nonce };
  return askJson(testUrl + `/account/api/im/?action=LOGIN_SIGN&timestamp=${timestamp}&nonce=${nonce}`).then((data) => {
    res.signature = data.data.sign;
    return function () {
      return res;
    };
  })
};


//获取用户信息
export function getUserInfor(conversationList) {
  let ll = [];
  for (let i of conversationList) {
    for (let j of i.members) {
      ll.push(_getUserInfor(j));
    }
  }
  return Promise.all(ll)
}

function _getUserInfor(id) {
  if (userInfor[id]) {
    return;
  }
  return askJson(testUrl + `/account/api/user/${id}/`).then((d) => {
    if (d.detail) {
      throw new Error();
    }
    userInfor[id] = d;
    if (d.username && d.username.substr(0, 2) === "oU") {
      d.username = "用户" + id
    }
    return "succes";
  }).catch((e) => {
    console.log(`获取用户信息失败！id:${id}`);
    userInfor[id] = {
      "avatar_img_url": "/static/img/MAIMAI.jpg",
      "username": "用户" + id,
    }
    return "fail";
  })
}



// 计算时间差
export function handleDate(dateTimeStamp) {
  var result = '';
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp.getTime();
  if (diffValue < 0) {
    console.log("时间不对劲,服务器创建时间与当前时间不同步");
    return result = "刚刚";
  }
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  if (parseInt(dayC) > 30) {
    result = "" + format(dateTimeStamp, "yyyy-MM-dd");
  } else if (parseInt(dayC) > 1) {
    result = "" + parseInt(dayC) + "天前";
  } else if (parseInt(dayC) == 1) {
    result = "昨天";
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else
    result = "刚刚";
  return result;
}

/**
 * 格式化时间
 * @param date Date 时间
 * @param format 格式化 "yyyy-MM-dd hh:mm:ss www"=format
 * @returns {string} 格式化后字符串
 */
export function format(date, format) {
  if (typeof date == 'string') {
    if (date.indexOf('T') >= 0) {
      date = date.replace('T', ' ')
    }
    date = new Date(Date.parse(date.replace(/-/g, "/")))
  }
  else if (typeof date === "object") {
    date = date;
  }
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  };
  var w = [
    ['日', '一', '二', '三', '四', '五', '六'],
    ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  ];
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  if (/(w+)/.test(format)) {
    format = format.replace(RegExp.$1, w[RegExp.$1.length - 1][date.getDay()]);
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
}

export function askJson(url, obj, TimeOut) {
  if (obj && Reflect.has(obj, "body")) {
    let body = new FormData();
    for (let i of Reflect.ownKeys(obj.body)) {
      body.append(i, obj["body"][i]);
    }
    obj = { ...obj, credentials: 'include', body: body }
  }
  else {
    obj = { ...obj, credentials: 'include' }
  }

  let req = fetch(url, obj).then((res) => {
    return res.json();
  })
  if (TimeOut) {
    let TO = new Promise((r, c) => {
      setTimeout(() => {
        c("请求超时！");
      }, TimeOut)
    })
    return Promise.race([req, TO]);
  }
  else {
    return req;
  }
}

export function getPar(par) {
  //获取当前URL
  var local_url = document.location.href;
  //获取要取得的get参数位置
  var get = local_url.indexOf(par + "=");
  if (get == -1) {
    return false;
  }
  //截取字符串
  var get_par = local_url.slice(par.length + get + 1);
  //判断截取后的字符串是否还有其他get参数
  var nextPar = get_par.indexOf("&");
  if (nextPar != -1) {
    get_par = get_par.slice(0, nextPar);
  }
  return get_par;
}